package codeTop;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

public class q402 {
    public String removeKdigits(String num, int k) {
        Stack<Character> stack = new Stack<>();
        int n = 0;
        for (int i = 0; i < num.length(); i++) {
            while (!stack.isEmpty() && stack.peek() > num.charAt(i)&&n<k) {
                stack.pop();
                n++;
            }
            stack.push(num.charAt(i));
        }
        while (n < k) {
            stack.pop();
            n++;
        }
        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        while (!sb.isEmpty()&&sb.charAt(sb.length() - 1) == '0') {
            sb.deleteCharAt(sb.length()-1);
        }
        return sb.isEmpty()?"0":sb.reverse().toString();
    }
}
